﻿using Autodesk.AutoCAD.DatabaseServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CADDemo2025
{
    public static class EmEntityMethod
    {
        public static void AddEntities<T>(this List<T> ents) where T : Entity
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tran = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite);
                foreach (var item in ents)
                {
                    if (item.IsNewObject)
                    {
                        var id = btr.AppendEntity(item);
                        tran.AddNewlyCreatedDBObject(item, true);
                    }
                }
                tran.Commit();
            }
        }
        public static void AddEntity(this Entity ent, int n = 0)
        {
            AddEntities(new List<Entity>() { ent });
        }
        public static void EditEntities<T>(this List<T> entity, Action action) where T : Entity
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tran = db.TransactionManager.StartTransaction())
            {
                entity.ForEach(e => e.ObjectId.GetObject(OpenMode.ForWrite));
                action();
                tran.Commit();
            }
        }
        public static void EditEntity(this Entity entity, Action action)
        {
            EditEntities(new List<Entity>() { entity }, action);
        }
        public static void EraseEntities<T>(this List<T> ents) where T : Entity
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tran = db.TransactionManager.StartTransaction())
            {
                foreach (var item in ents)
                {
                    item.ObjectId.GetObject(OpenMode.ForWrite);
                    if (item.IsErased) continue;
                    if (item.ObjectId == ObjectId.Null) continue;
                    item.Erase();
                }
                tran.Commit();
            }
        }
        public static void EraseEntity<T>(this T ent) where T : Entity
        {
            EraseEntities(new List<T>() { ent });
        }
    }
}
